package com.whjk.system.data.uitls.pdfUtils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class TjReportFooter extends PdfPageEventHelper {
    // 总页数
    private PdfTemplate totalPage;
    private String phone;
    private String name;
    private String sex;
    private String age;
    private String itemName;
    private Date day;
    private String regSerialNo;
    private String now = DateUtil.today();
    private Boolean isShow = true;
    public BaseFont bf;
    public String filename;
    public Boolean p;

    /**
     * 页眉logo
     */
    private String url;

    public TjReportFooter(String regSerialNo, String phone, String name, String sex, String age, String itemName, Date day) {
        this.phone = phone;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.itemName = itemName;
        this.day = day;
        this.regSerialNo = regSerialNo;
    }


    public TjReportFooter(String regSerialNo, String phone, String name, String sex, String age, String itemName, Date day, Boolean isShow) {
        this.phone = phone;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.itemName = itemName;
        this.day = day;
        this.regSerialNo = regSerialNo;
        this.isShow = isShow;
    }

    /**
     * 钟祥
     *
     * @param regSerialNo
     * @param phone
     * @param name
     * @param sex
     * @param age
     * @param itemName
     * @param day
     * @param isShow
     */
    public TjReportFooter(String url, String regSerialNo, String phone, String name, String sex, String age, String itemName, Date day, Boolean isShow) {
        this.phone = phone;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.itemName = itemName;
        this.day = day;
        this.regSerialNo = regSerialNo;
        this.isShow = isShow;
        this.url = url;

    }

    public TjReportFooter() {
        this.phone = "默认值";
        this.name = "默认值";
        this.sex = "默认值";
        this.age = "默认值";
        this.itemName = "默认值";
        this.day = new Date();
    }

    public TjReportFooter(String filename) {
        this.filename = filename;
    }

    // 打开文档时，创建一个总页数的模版
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        totalPage = cb.createTemplate(30, 20);
        try {
            bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }

    // 一页加载完成触发，写入页眉和页脚
    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        System.out.println(writer.getPageNumber() + "-----------------------------");
        try {
            if (writer.getPageNumber() == 1) {
                //  createNameTable(writer, document);

/*                PdfPTable table = PdfTable.createTable(new int[]{100});
                table.addCell(PdfTable.createCellDiyBor("", PdfFont.getTitle(10), PdfTable.borX, PdfTable.padding4));
                table.addCell(PdfTable.createCellDiyBor(CommonConstants.HOSPITAL_NAME, PdfFont.getTitle(10), PdfTable.notBor, PdfTable.padding4));
                table.addCell(PdfTable.createCellDiyBor("咨询电话: 15271744563", PdfFont.getTitle(10), PdfTable.notBor, PdfTable.padding4));
                table.addCell(PdfTable.createCellDiyBor("本体检报告仅供临床参考,不作为诊断依据,谢谢您的光临", PdfFont.getTitle(10), PdfTable.notBor, PdfTable.padding4));

                table.writeSelectedRows(0, -1, 50, 50, writer.getDirectContent());*/
                return;
            }
            if (isShow) {
                //非首页页眉
                PdfPTable yemei = PdfTable.createTable(new int[]{1, 10});
                String s1 = filename + "/1.png";
                File fileImg2 = new File(s1);
                PdfPCell cell;
                if (fileImg2.exists()) {
                    Image image = Image.getInstance(filename + "/1.png");
                    image.setAlignment(Image.ALIGN_CENTER);
                    //表格图片是根据表格高度
                    // int height = (int) Math.ceil(image.getHeight());
                    cell = PdfTable.createCell(image, 10, 0, PdfTable.borX);
                } else {
                    cell = PdfTable.createCell("", 10, 0, PdfTable.borX);
                }
                // 设置单元格高度
                cell.setFixedHeight(40);
                yemei.addCell(cell);
                yemei.addCell(PdfTable.createCell("赣州市经开区第二人民医院（湖边镇卫生院） 健康体检报告", 12, 0, PdfTable.borX));
                // 将页眉写到document中，
                yemei.writeSelectedRows(0, -1, 50 + 15, PageSize.A4.getHeight() - 10, writer.getDirectContent());
            }

            //非首页页脚
            PdfPTable yejiao = PdfTable.createTable(new int[]{1});
            yejiao.addCell(PdfTable.createCell("把我们的关怀送到您的心中", 10, 0, PdfTable.borS));
            //  yejiao.addCell(PdfTable.createCell("打印时间:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:dd"), 10, 2, PdfTable.borS));
            yejiao.writeSelectedRows(0, -1, 65, 50, writer.getDirectContent());

            //在每页结束的时候把“第x页”信息写道模版指定位置
            PdfContentByte cb = writer.getDirectContent();
            cb.saveState();
            String text = "第" + writer.getPageNumber() + "页,共    页";
            cb.beginText();
            cb.setFontAndSize(bf, 10);
            // 定位“第x页,共” 在具体的页面调试时候需要更改这xy的坐标
            cb.setTextMatrix(270, 35);
            cb.showText(text);
            cb.endText();
            // 定位“y页” 在具体的页面调试时候需要更改这xy的坐标
            cb.addTemplate(totalPage, 307, 35);
            // cb.saveState();
            cb.stroke();
            cb.restoreState();
            cb.closePath();//sanityCheck();
        } catch (Exception de) {
            throw new ExceptionConverter(de);
        }
    }

    /**
     * 全部完成后，将总页数的pdf模版写到指定位置
     *
     * @param writer
     * @param document
     */
    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        //  String text = "总" + (writer.getPageNumber()) + "页";
        // ColumnText.showTextAligned(totalPage, Element.ALIGN_LEFT, new Paragraph(text,PdfFont.getNormal(PdfFont.baseFontMap.get("bfChinese"),8)), 2, 2, 0);
        totalPage.beginText();
        totalPage.setFontAndSize(bf, 10);
        totalPage.showText(String.valueOf(writer.getPageNumber()));
        totalPage.endText();
        totalPage.closePath();//sanityCheck();
    }

    void createNameTable(PdfWriter writer, Document document) {
        PdfPTable tableName = PdfTable.createTable(new int[]{3, 3, 6, 5});
        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("姓          名:", 13, 1));
        tableName.addCell(PdfTable.createCell(name, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("性          别:", 13, 1));
        tableName.addCell(PdfTable.createCell(sex, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("年          龄:", 13, 1));
        tableName.addCell(PdfTable.createCell(age, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("体   检   号:", 13, 1));
        tableName.addCell(PdfTable.createCell(regSerialNo, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("联系电话:", 13, 1));
        tableName.addCell(PdfTable.createCell(phone, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("体检日期:", 13, 1));
        String s = day != null ? new SimpleDateFormat("yyyy年MM月dd日").format(day) : "";
        tableName.addCell(PdfTable.createCell(s, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

        tableName.addCell(PdfTable.createCell("", 13, 1));
        tableName.addCell(PdfTable.createCell("单          位:", 13, 1));
        tableName.addCell(PdfTable.createCell(itemName, 13, 0));
        tableName.addCell(PdfTable.createCell("", 13, 1));

/*        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("联系电话:"));
        tableName.addCell(PdfTable.createCellNotBor(phone,0));
        tableName.addCell(PdfTable.createCellNotBor(""));*/

        for (int i = 0; i < 5; i++) {
            tableName.addCell(PdfTable.createCellNotBor("  "));
            tableName.addCell(PdfTable.createCellNotBor("  "));
            tableName.addCell(PdfTable.createCellNotBor("  "));
            tableName.addCell(PdfTable.createCellNotBor("  "));
        }

        tableName.writeSelectedRows(0, -1, document.left(document.leftMargin() - 70), tableName.getTotalHeight() + document.bottom(document.bottomMargin() + 130), writer.getDirectContent());

        PdfPTable tableName2 = PdfTable.createTable(new int[]{1});
        tableName2.addCell(PdfTable.createCell(" ", 13, 0, PdfTable.borS));
        tableName2.addCell(PdfTable.createCell("备注：如果您对本次体检结果有异议，请于一周内持体检报告到我科查询。", 13, 0));
        tableName2.addCell(PdfTable.createCell("健康咨询电话：0717-6922632", 13, 0));
        tableName2.addCell(PdfTable.createCell("健康咨询时间：周一到周五下午：2：30-5：00", 13, 0));

        tableName2.writeSelectedRows(0, -1, document.left(document.leftMargin() - 150), tableName.getTotalHeight() + document.bottom(document.bottomMargin() - 250), writer.getDirectContent());




/*


        PdfPTable tr = PdfTable.createTablTotalWidthe(new int[]{4, 3, 2, 4},200);
        tr.addCell(PdfTable.createCellNotBor("体   检  号:",0,PdfTable.baseColorLightGray,60));
        tr.addCell(PdfTable.createCellNotBor(regSerialNo,0,PdfTable.baseColorLightGray,0));
        tr.addCell(PdfTable.createCellNotBor("联系电话:",0,PdfTable.baseColorLightGray,0));
        tr.addCell(PdfTable.createCellNotBor(phone,0,PdfTable.baseColorLightGray,0));


        tr.addCell(PdfTable.createCellNotBor("出生日期:",0,PdfTable.baseColorLightGray,60));
        String ss = birthday != null ? new SimpleDateFormat("yyyy年MM月dd日").format(birthday) : "";
        tr.addCell(PdfTable.createCellNotBor(ss,0,PdfTable.baseColorLightGray,0));
        tr.addCell(PdfTable.createCellNotBor("婚          姻:",0,PdfTable.baseColorLightGray,0));
        tr.addCell(PdfTable.createCellNotBor("",0,PdfTable.baseColorLightGray,0));

        tr.addCell(PdfTable.createCellNotBor("备          注:",0,PdfTable.baseColorLightGray,60));
        tr.addCell(PdfTable.createCellNotBor("",0,PdfTable.baseColorLightGray,0));
        tr.addCell(PdfTable.createCellNotBor("",0,PdfTable.baseColorLightGray,0));
        tr.addCell(PdfTable.createCellNotBor("",0,PdfTable.baseColorLightGray,0));
        for (int i = 0; i < 5; i++) {
            tr.addCell(PdfTable.createCellNotBor("  "));
            tr.addCell(PdfTable.createCellNotBor("  "));
            tr.addCell(PdfTable.createCellNotBor("  "));
            tr.addCell(PdfTable.createCellNotBor("  "));
        }

        tr.writeSelectedRows(0, -1, document.left(document.leftMargin()-100), tr.getTotalHeight() + document.bottom(document.bottomMargin()-80), writer.getDirectContent());

*/


        /*        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("年          龄:"));
        tableName.addCell(PdfTable.createCellX(age));
        tableName.addCell(PdfTable.createCellNotBor(""));

        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("性          别:"));
        tableName.addCell(PdfTable.createCellX(sex));
        tableName.addCell(PdfTable.createCellNotBor(""));*/
        /*PdfPTable tableName = PdfTable.createTable(new int[]{3, 3, 6, 5});
        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("姓          名:"));
        tableName.addCell(PdfTable.createCellNotBor(name+"      "+sex+"      "+age,0));
        tableName.addCell(PdfTable.createCellNotBor(""));

        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("体检日期:"));
        String s = day != null ? new SimpleDateFormat("yyyy年MM月dd日").format(day) : "";
        tableName.addCell(PdfTable.createCellNotBor(s,0));
        tableName.addCell(PdfTable.createCellNotBor(""));

        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("单          位:"));
        tableName.addCell(PdfTable.createCellNotBor(itemName,0));
        tableName.addCell(PdfTable.createCellNotBor(""));

        tableName.addCell(PdfTable.createCellNotBor(""));
        tableName.addCell(PdfTable.createCellNotBor("联系电话:"));
        tableName.addCell(PdfTable.createCellNotBor(phone,0));
        tableName.addCell(PdfTable.createCellNotBor(""));

        for (int i = 0; i < 5; i++) {
            tableName.addCell(PdfTable.createCellNotBor("  "));
            tableName.addCell(PdfTable.createCellNotBor("  "));
            tableName.addCell(PdfTable.createCellNotBor("  "));
            tableName.addCell(PdfTable.createCellNotBor("  "));
        }

        tableName.writeSelectedRows(0, -1, document.left(document.leftMargin() - 100), tableName.getTotalHeight() + document.bottom(document.bottomMargin()-80), writer.getDirectContent());
   */
    }


    /**
     * InputStream 转 byte[]
     *
     * @param is
     * @return
     */
    public static byte[] getContent(InputStream is) {
        if (is == null) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            //byte[] buffer = new byte[16 * 1024];
            while (true) {
                int len = is.read(buffer);
                if (len == -1) {
                    break;
                }
                baos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(baos);
            IoUtil.close(is);
        }
        return baos.toByteArray();
    }
}
